﻿using Baidu.Aip.Demo;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.IO;
using PDFLibNet;

namespace PicRec
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        private NotifyIcon notifyIcon = null;
        public MainWindow()
        {
            InitializeComponent();

            InitIcon();
            fileDialog.Title = "请选择图片";
            fileDialog.Filter = "图片|*.jpg;*.png";
        }

        public OpenFileDialog fileDialog = new OpenFileDialog();

        /// <summary>
        /// 图标初始化
        /// </summary>
        private void InitIcon()
        {
            this.notifyIcon = new NotifyIcon();
            this.notifyIcon.BalloonTipText = "欢迎使用图像识别"; //设置程序启动时显示的文本
            this.notifyIcon.Text = "图像识别，Designed by Fly Cheng";//最小化到托盘时，鼠标点击时显示的文本
            this.notifyIcon.Icon = new System.Drawing.Icon("icon.ico");//程序图标
            this.notifyIcon.Visible = true;
            notifyIcon.MouseClick += OnNotifyIconLeftClick;
            this.notifyIcon.ShowBalloonTip(1000);
            InitIconMenu();

        }

        /// <summary>
        /// 图标左键单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNotifyIconLeftClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            this.WindowState = WindowState.Normal;
        }

        /// <summary>
        /// 初始化图标菜单
        /// </summary>
        private void InitIconMenu()
        {
            System.Windows.Forms.MenuItem m1 = new System.Windows.Forms.MenuItem("显示");
            m1.Click += MenuClick;

            System.Windows.Forms.MenuItem m2 = new System.Windows.Forms.MenuItem("隐藏");
            m2.Click += MenuClick;

            System.Windows.Forms.MenuItem m3 = new System.Windows.Forms.MenuItem("退出");
            m3.Click += MenuClick;

            System.Windows.Forms.MenuItem[] m = new System.Windows.Forms.MenuItem[] { m1, m2, m3 };
            this.notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(m);
        }

        //图标菜单单击事件
        private void MenuClick(object sender, EventArgs e)
        {
            System.Windows.Forms.MenuItem m = (System.Windows.Forms.MenuItem)sender;
            string opt = m.Text;
            switch (opt)
            {
                case "显示":
                    this.WindowState = WindowState.Normal;
                    break;
                case "隐藏":
                    this.WindowState = WindowState.Minimized;
                    break;
                case "退出":
                    this.Close();
                    break;
            }
        }

        /// <summary>
        /// 选择图片事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChoose_Click(object sender, RoutedEventArgs e)
        {
            
            fileDialog.Multiselect = true;
            //fileDialog.Title = "请选择图片";
            //fileDialog.Filter = "图片/PDF文件|*.jpg;*.png";
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] files = fileDialog.FileNames;
                string sb = "";
                if (files != null && files.Length > 0)
                {
                    foreach (string f in files)
                    {
                        sb = sb + f + ";";
                    }
                }
                if (sb.Length > 0)
                {

                    sb = sb.Substring(0, sb.Length - 1);
                }
                tbFileName.Text = sb;
            }

        }

        /// <summary>
        /// 开始识别图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.WorkerSupportsCancellation = true; //可以取消
            bgw.DoWork += new DoWorkEventHandler(ThreadStart);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ThreadCompleted);
            bgw.RunWorkerAsync();
        }

        /// <summary>
        /// 线程开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ThreadStart(object sender, DoWorkEventArgs e)
        {
            string recType = "";
            int fileNameLength = 0;

            

            cbType.Dispatcher.Invoke(new Action(() => { recType = cbType.Text; }));
            tbFileName.Dispatcher.Invoke(new Action(() => { fileNameLength = tbFileName.Text.Trim().Length; }));
            if (fileNameLength == 0)
            {
                System.Windows.MessageBox.Show("请选择图片后再进行识别！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            progressbar.Dispatcher.Invoke(new Action(() => { progressbar.IsIndeterminate = true; }));
            //tbResult.Text = "";
            switch (recType)
            {
                case "识别文字":
                    RecWord();
                    break;
                case "识别PDF":
                    RecPDF();
                    break;
                case "识别身份证":
                    RecIdCard();
                    break;
                case "识别银行卡":
                    RecBandCard();
                    break;
                case "识别驾驶证":
                    RecDrivingLicense();
                    break;
                case "识别营业执照":
                    RecBusinessLicense();
                    break;
                case "识别车牌号":
                    RecCarNumber();
                    break;
            }
            tbResult.Dispatcher.Invoke(new Action(() => { tbResult.Focus(); }));
            progressbar.Dispatcher.Invoke(new Action(() => { progressbar.IsIndeterminate = false; }));
        }

        // <summary>
        /// 线程完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ThreadCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        //识别身份证
        public void RecIdCard()
        {
            if (tbFileName.Text.Length > 0)
            {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath1 = fileNames[0];
                    string imgPath2 = null;
                    if (fileNames.Length > 1)
                    {
                        imgPath2 = fileNames[1];
                    }
                    result = OcrDemo.Idcard(imgPath1, imgPath2);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
            }
        }

        //识别银行卡
        public void RecBandCard()
        {
            if (tbFileName.Text.Length > 0)
            {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath = fileNames[0];
                    result = OcrDemo.PlateLicense(imgPath);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
            }
        }

        //识别驾驶证
        public void RecDrivingLicense()
        {
            if (tbFileName.Text.Length > 0)
            {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath = fileNames[0];
                    result = OcrDemo.DrivingLicense(imgPath);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
            }
        }

        //识别行驶证
        public void RecVehicleLicense()
        {
            if (tbFileName.Text.Length > 0)
            {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath = fileNames[0];
                    result = OcrDemo.VehicleLicense(imgPath);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
            }
        }

        //识别营业执照
        public void RecBusinessLicense()
        {
            if (tbFileName.Text.Length > 0)
            {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath = fileNames[0];
                    result = OcrDemo.BusinessLicense(imgPath);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
            }
        }

        //识别车牌号
        public void RecCarNumber()
        {
                string[] fileNames = tbFileName.Text.Split(';');
                if (fileNames.Length > 0)
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                    string result = "";
                    string imgPath = fileNames[0];
                    result = OcrDemo.PlateLicense(imgPath);
                    tbResult.Text = result;
                    lbStatus.Content = "识别完成";
                    color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }
        }

        //识别文字
        public void RecWord()
        {
            string[] fileNames = null;
            tbFileName.Dispatcher.Invoke(new Action(() => { fileNames = tbFileName.Text.Split(';'); }));
            if (fileNames.Length > 0)
            {
                lbStatus.Dispatcher.Invoke(new Action(() =>
                {
                    lbStatus.Content = "识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }));

                string word = "";
                string recWordType = "";
                cbRecWordType.Dispatcher.Invoke(new Action(() => { recWordType = cbRecWordType.Text; }));
                foreach (string f in fileNames)
                {
                    switch (recWordType)
                    {
                        case "高精度版":
                            word = word + OcrDemo.Accurate(f) + "\r\n\r\n";
                            break;
                        case "高精度含位置版":
                            word = word + OcrDemo.AccurateWithLocation(f) + "\r\n\r\n";
                            break;
                        case "普通版":
                            word = word + OcrDemo.GeneralBasic(f, true) + "\r\n\r\n";
                            break;
                        case "普通含位置版":
                            word = word + OcrDemo.GeneralWithLocatin(f) + "\r\n\r\n";
                            break;
                    }
                }
                tbResult.Dispatcher.Invoke(new Action(() => { tbResult.Text = word; }));
                lbStatus.Dispatcher.Invoke(new Action(() =>
                {
                    lbStatus.Content = "识别完成";
                    Color color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }));

            }
        }

        //识别PDF
        public void RecPDF()
        {
            string[] fileNames = null;
            tbFileName.Dispatcher.Invoke(new Action(() => { fileNames = tbFileName.Text.Split(';'); }));
            if (fileNames.Length > 0)
            {
                lbStatus.Dispatcher.Invoke(new Action(() =>
                {
                    lbStatus.Content = "PDF转换图片中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }));

                string word = "";
                string recWordType = "";
                cbRecWordType.Dispatcher.Invoke(new Action(() => { recWordType = cbRecWordType.Text; }));
                string PdfFilePath=fileNames[0];
                string targetFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tmpFolder");
                string pageNum = "";
                TbPdfNum.Dispatcher.Invoke(new Action(() => { pageNum = TbPdfNum.Text; }));
                PDFSplit2Jpg(PdfFilePath, targetFolder,pageNum);

                lbStatus.Dispatcher.Invoke(new Action(() =>
                {
                    lbStatus.Content = "PDF识别中...";
                    Color color = (Color)ColorConverter.ConvertFromString("Red");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }));

                string[] imgFiles= Directory.GetFiles(targetFolder);
                if (imgFiles != null && imgFiles.Length > 0)
                {
                    foreach (string f in imgFiles)
                    {
                        switch (recWordType)
                        {
                            case "高精度版":
                                word = word + OcrDemo.Accurate(f) + "\r\n\r\n";
                                break;
                            case "高精度含位置版":
                                word = word + OcrDemo.AccurateWithLocation(f) + "\r\n\r\n";
                                break;
                            case "普通版":
                                word = word + OcrDemo.GeneralBasic(f, true) + "\r\n\r\n";
                                break;
                            case "普通含位置版":
                                word = word + OcrDemo.GeneralWithLocatin(f) + "\r\n\r\n";
                                break;
                        }
                    }
                }

                if (imgFiles != null && imgFiles.Length > 0)
                {
                    foreach (string f in imgFiles)
                    {
                        File.Delete(f);
                    }
                }

                tbResult.Dispatcher.Invoke(new Action(() => { tbResult.Text = word; }));
                lbStatus.Dispatcher.Invoke(new Action(() =>
                {
                    lbStatus.Content = "识别完成";
                    Color color = (Color)ColorConverter.ConvertFromString("Green");
                    lbStatus.Foreground = new SolidColorBrush(color);
                }));               
            }
        }

        /// <summary>
        /// 识别类型事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count == 0)
            {
                return;
            }
            string selectedText = ((ComboBoxItem)cbType.SelectedItem).Content.ToString();
            if (selectedText == "识别身份证")
            {
                lbTip.Content = "注：若要识别身份证正反面，需第一张为正面，第二张为反面";
                lbTip.Visibility = Visibility.Visible;
            }
            else
            {
                lbTip.Visibility = Visibility.Collapsed;
            }

            if (selectedText == "识别文字"||selectedText=="识别PDF")
            {
                lbTip.Content = "注：高精度版、高精度含位置、普通版、普通含位置版每天有50、50、500、500次限制";
                lbTip.Visibility = Visibility.Visible;
                cbRecWordType.Visibility = Visibility.Visible;
            }
            else
            {
                cbRecWordType.Visibility = Visibility.Collapsed;
            }

            if (selectedText == "识别文字")
            {
                btnChoose.Content = "选择图片";
                fileDialog.Title = "请选择图片";
                fileDialog.Filter = "图片|*.jpg;*.png";
            }
            if (selectedText == "识别PDF")
            {
                lbPdfNum.Visibility = Visibility.Visible;
                TbPdfNum.Visibility = Visibility.Visible;
                btnChoose.Content = "选择PDF";
                fileDialog.Title = "请选择PDF";
                fileDialog.Filter = "PDF文件|*.pdf;*.PDF";
            }
            else
            {
                lbPdfNum.Visibility = Visibility.Collapsed;
                TbPdfNum.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// PDF有多少页拆分成多少个jpg文件
        /// </summary>
        /// <param name="file">要拆分的PDF文件路径</param>
        /// <param name="targetFolder">拆分后生成的PDF文件存放路径</param>
        /// <param name="results"></param>
        public void PDFSplit2Jpg(string file, string targetFolder,string pageNum)
        {
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }

            string[] imgFiles = Directory.GetFiles(targetFolder);

            if (imgFiles != null && imgFiles.Length > 0)
            {
                foreach (string f in imgFiles)
                {
                    File.Delete(f);
                }
            }
            try
            {
                if (string.IsNullOrEmpty(file))
                {
                    return;
                }

                if (Directory.GetFiles(targetFolder).Length > 0)
                {
                    foreach (string f in Directory.GetFiles(targetFolder))
                    {
                        File.Delete(f);
                    }
                }
                PDFWrapper pdfWrapper = new PDFWrapper();
                pdfWrapper.LoadPDF(file);

                int pagecount = pdfWrapper.PageCount == 0 ? 1 : pdfWrapper.PageCount;
                int Dpi = 150, Qua = 90;
                if (pageNum == null || pageNum.Length == 0)
                {
                    for (int i = 1; i <= pagecount; i++)
                    {
                        pdfWrapper.ExportJpg(System.IO.Path.Combine(targetFolder, i + ".jpg"), i, i, Dpi, Qua);//这里可以设置输出图片的页数、大小和图片质量
                        while (pdfWrapper.IsJpgBusy)
                        {
                            Thread.Sleep(5);
                        }
                    }
                }
                else if (pageNum.Contains(' '))
                {
                    string[] pages = pageNum.Split(' ');
                    List<int> pageList = new List<int>();
                    try
                    {
                        foreach (string page in pages)
                        {
                            int p = Int32.Parse(page);
                            pageList.Add(p);
                        }
                    }
                    catch(Exception e)
                    {
                        System.Windows.MessageBox.Show("指定页码格式错误");
                        return;
                    }
                    foreach(int p in pageList)
                    {
                        if (p < pagecount)
                        {
                            pdfWrapper.ExportJpg(System.IO.Path.Combine(targetFolder, p + ".jpg"), p, p, Dpi, Qua);//这里可以设置输出图片的页数、大小和图片质量
                            while (pdfWrapper.IsJpgBusy)
                            {
                                Thread.Sleep(5);
                            }
                        }
                    }
                }
                else if (pageNum.Contains('-'))
                {
                    int start = 0;
                    int end = 0;
                    try
                    {
                        start = Int32.Parse(pageNum.Split('-')[0]);
                        end = Int32.Parse(pageNum.Split('-')[1]);
                    }
                    catch (Exception e)
                    {
                        System.Windows.MessageBox.Show("指定页码格式错误");
                        return;
                    }
                    for (int i = start; i <= end; i++)
                    {
                        pdfWrapper.ExportJpg(System.IO.Path.Combine(targetFolder, i + ".jpg"), i, i, Dpi, Qua);//这里可以设置输出图片的页数、大小和图片质量
                        while (pdfWrapper.IsJpgBusy)
                        {
                            Thread.Sleep(5);
                        }
                    }
                }
                
                
                pdfWrapper.Dispose();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show("程序异常");
            }
        }
    }
}
